package com.pkx.guide.common.result;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pkx.guide.common.annotation.ORpose;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author sunsy
 */
@RestControllerAdvice
@Order( Ordered.LOWEST_PRECEDENCE )
public class RposeHdler implements ResponseBodyAdvice<Object> {
    private static final Logger LOG = LoggerFactory.getLogger( RposeHdler.class.getName() );
    @Resource
    private ObjectMapper omper;

    public ObjectMapper getOmper() {
        return omper;
    }

    public void setOmper(ObjectMapper omper) {
        this.omper = omper;
    }

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        if( returnType.getGenericParameterType().equals(Result.class) ){
            return false;
        }
        if (returnType.getDeclaringClass().isAnnotationPresent(ORpose.class) || returnType.getMethod().isAnnotationPresent(ORpose.class)) {
            return true;
        }
        return false;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        Result orp = Result.success( body );
        if( returnType.getGenericParameterType().equals(String.class) ){
            try {
                response.getHeaders().setContentType(MediaType.parseMediaType(MediaType.APPLICATION_JSON_VALUE));
                return getOmper().writeValueAsString( orp );
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return orp;
    }
}
